package com.itcam.tingshu.payment.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itcam.tingshu.common.constant.KafkaConstant;
import com.itcam.tingshu.common.constant.SystemConstant;
import com.itcam.tingshu.common.service.KafkaService;
import com.itcam.tingshu.model.payment.PaymentInfo;
import com.itcam.tingshu.payment.mapper.PaymentInfoMapper;
import com.itcam.tingshu.payment.service.PaymentInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wechat.pay.java.service.payments.model.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;

@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class PaymentInfoServiceImpl extends ServiceImpl<PaymentInfoMapper, PaymentInfo> implements PaymentInfoService {

    @Autowired
    private PaymentInfoMapper paymentInfoMapper;

    @Autowired
    private KafkaService kafkaService;

    /**
     * 保存交易记录
     * @param paymentType
     * @param userId
     * @param orderNo
     * @param totalAmount
     */
    @Override
    public void savePaymentInfo(String paymentType, Long userId, String orderNo, BigDecimal totalAmount) {
        // 可以利用orderNo去重操作
        // 创建对象
        PaymentInfo paymentInfo = new PaymentInfo();
        // 属性赋值
        paymentInfo.setUserId(userId); // 用户id
        paymentInfo.setPaymentType(paymentType); // 支付类型
        paymentInfo.setOrderNo(orderNo); // 订单号
        paymentInfo.setPayWay(SystemConstant.ORDER_PAY_WAY_WEIXIN); // 支付方式
        paymentInfo.setPaymentStatus(SystemConstant.ORDER_PAY_WAY_WEIXIN); // 支付状态
        paymentInfo.setAmount(totalAmount); // 支付金额
        String content = paymentType.equals(SystemConstant.PAYMENT_TYPE_ORDER) ? "支付订单" : "支付充值";
        paymentInfo.setContent(content);
        paymentInfo.setPaymentStatus(SystemConstant.PAYMENT_STATUS_UNPAID);
        // 保存数据
        paymentInfoMapper.insert(paymentInfo);
    }

    /**
     * 更新支付状态
     * @param result
     */
    @Override
    public void updatePaymentStatus(Transaction result) {
        // 先修改paymentInfo状态
        PaymentInfo paymentInfoQuery = paymentInfoMapper.selectOne(new LambdaQueryWrapper<PaymentInfo>().eq(PaymentInfo::getOrderNo, result.getOutTradeNo()));
        paymentInfoQuery.setPaymentStatus(SystemConstant.PAYMENT_STATUS_PAID);
        paymentInfoQuery.setOutTradeNo(result.getTransactionId());
        paymentInfoQuery.setCallbackTime(new Date());
        paymentInfoQuery.setCallbackContent(result.toString());
        paymentInfoMapper.updateById(paymentInfoQuery);
        // 发送消息修改订单状态或充值状态
        String topics = paymentInfoQuery.getPaymentType().equals(SystemConstant.PAYMENT_TYPE_ORDER) ? KafkaConstant.QUEUE_ORDER_PAY_SUCCESS : KafkaConstant.QUEUE_RECHARGE_PAY_SUCCESS;
        // 发送消息
        kafkaService.sendMsg(topics, result.getOutTradeNo());
    }
}
